﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using UnityEditor;


public class VoiceEditor : EditorWindow
{

    /// <summary>
	/// 当前编辑器窗口实例
	/// </summary>
	private static VoiceEditor instance;

    private static string componentName="MyButton";

    private static string voiceName = "Button01";

    /// <summary>
    /// 选中的预制体
    /// </summary>
    private static List<GameObject> selectedPrefabs;
   

    private void OnGUI()
    {
        DrawOptions();
        DrawAction();
    }

    private void Update()
    {
       
    }

    /// <summary>
	/// 绘制插件界面配置项
	/// </summary>
	private void DrawOptions()
    {
        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("请输入添加按钮声音的组件:", GUILayout.Width(200));
        componentName = EditorGUILayout.TextField(componentName, GUILayout.Width(200));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("请输入按钮的声音名称", GUILayout.Width(200));
        voiceName = EditorGUILayout.TextField(voiceName, GUILayout.Width(200));
        GUILayout.EndHorizontal();
    }

    /// <summary>
    /// 绘制界面的动作
    /// </summary>    
    private void DrawAction()
    {
        if (selectedPrefabs != null && selectedPrefabs.Count > 0)
        {
            GUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("选中的预制体:", GUILayout.Width(200));
            string objNames = "";
            selectedPrefabs.ForEach(i => {
                objNames += i.name + "\r\n";
            });         
            EditorGUILayout.TextArea(objNames, GUILayout.Width(200),GUILayout.Height(selectedPrefabs.Count==1?18: selectedPrefabs.Count*16));

            
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("添加组件"))
            {
                for (int i = 0; i < selectedPrefabs.Count; i++)
                {
                    string path = AssetDatabase.GetAssetPath(selectedPrefabs[i]);
                    GameObject originPrefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;

                    if (originPrefab == null)
                        continue;

                    GameObject newPrefab = PrefabUtility.InstantiatePrefab(originPrefab) as GameObject;

                    PrefabUtility.UnpackPrefabInstanceAndReturnNewOutermostRoots(newPrefab, PrefabUnpackMode.Completely);

                    List<Transform> children = new List<Transform>();

                    GetAllChildByFilter(newPrefab.transform, componentName, children);

                    if (children.Count == 0)
                    {
                        DestroyImmediate(newPrefab);
                        continue;
                    }
                        
                    foreach (var child in children)
                    {
                        child.gameObject.AddComponent<ButtonVoice>()?.SetVoice(voiceName);
                    }                    

                    //替换预制体
                    PrefabUtility.ReplacePrefab(newPrefab, originPrefab);

                    DestroyImmediate(newPrefab);
                }

                EditorUtility.DisplayDialog("提示", "添加成功", "ok");
                EditorPrefs.SetString("componentName", componentName);
                EditorPrefs.SetString("voiceName",voiceName);
            }

            if (GUILayout.Button("移除组件"))
            {
                for (int i = 0; i < selectedPrefabs.Count; i++)
                {
                    string path = AssetDatabase.GetAssetPath(selectedPrefabs[i]);
                    GameObject originPrefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;

                    if (originPrefab == null)
                        continue;

                    GameObject newPrefab = PrefabUtility.InstantiatePrefab(originPrefab) as GameObject;

                    PrefabUtility.UnpackPrefabInstanceAndReturnNewOutermostRoots(newPrefab, PrefabUnpackMode.Completely);                    

                    List<Transform> children = new List<Transform>();

                    GetAllChildByFilter(newPrefab.transform, componentName, children);

                    if (children.Count == 0)
                    {
                        DestroyImmediate(newPrefab);
                        continue;
                    } 
                    foreach (var child in children)
                    {
                        DestroyImmediate(child.GetComponent<ButtonVoice>());
                    }

                    //替换预制体
                    PrefabUtility.ReplacePrefab(newPrefab, originPrefab);

                    DestroyImmediate(newPrefab);
                }

                EditorUtility.DisplayDialog("提示", "移除成功", "ok");
            }
            GUILayout.EndHorizontal();            
        }
    }

    private void GetAllChildByFilter(Transform tsf, string componentName,List<Transform>children)
    {        
        foreach (Transform child in tsf)
        {
            if (child.GetComponent(componentName)||child.GetComponent<Button>())
            {
                children.Add(child);
            }
            if (child.childCount > 0)
            {
                GetAllChildByFilter(child, componentName, children);
            }
        }       
    }

    /// <summary>
    /// 加载选中的预制体
    /// </summary>
    private static void LoadPrefab()
    {
        if (selectedPrefabs != null)
        {
            selectedPrefabs.Clear();
        }
        else
        {
            selectedPrefabs = new List<GameObject>();
        }               
        object[] objs = Selection.objects;
        if (objs.Length == 0)
        {
            return;
        }
        for (int i = 0; i < objs.Length; i++)
        {
            if(objs[i] as GameObject)
            {
                string path = AssetDatabase.GetAssetPath(objs[i] as GameObject);
                if(!string.IsNullOrEmpty(path))
                    selectedPrefabs.Add((GameObject)objs[i]);
            }            
        }
    }

    public static void Init()
    {
        //获取当前实例
        instance = EditorWindow.GetWindow<VoiceEditor>();
    }



    [MenuItem("VoiceTool/CreateVoiceManager")]
    static void CreateVoiceManager()
    {
        GameObject prefab = Resources.Load<GameObject>("Prefabs/VoiceManager");
        GameObject go = GameObject.Instantiate(prefab);
        go.name = "VoiceManager";
    }



    [MenuItem("VoiceTool/AddButtonVoice")]
    static void ShowVoiceEditor()
    {
        Init();
        LoadPrefab();
        componentName = EditorPrefs.GetString("componentName");
        voiceName = EditorPrefs.GetString("voiceName");
    }


    private void OnSelectionChange()
    {
        //当选择发生变化时重绘窗体
        Show();
        LoadPrefab();
        Repaint();
    }
    
}
